package com.cz.sharding;


import cn.hutool.core.date.DateField;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/readwrite")
public class TestReadwriteController {


    @Autowired
    private JdbcTemplate jdbcTemplate;

    @GetMapping("/insert")
    public void insert() {
        Date date = new Date();
        for (int i = 0; i < 100; i++) {
            String name = RandomUtil.randomString("李刚陈华钱胜耿经耳机", 2);
            String age = RandomUtil.randomNumbers(2);
            Date createTime = RandomUtil.randomDate(new Date(), DateField.DAY_OF_YEAR, -100, 100);
            Date updateTime = RandomUtil.randomDate(new Date(), DateField.DAY_OF_YEAR, -100, 100);
            jdbcTemplate.update("insert into sys_user (name,age,create_time,update_time) values (?,?,?,?)", name, age, createTime, updateTime);

        }
    }



    @Transactional
    @GetMapping("/insertTransaction")
    public void insertTransaction() {
        jdbcTemplate.query("select * from sys_user", (resultSet, i) -> {
            System.out.println(resultSet.getString("name"));
            return null;
        });
        String name = RandomUtil.randomString("李刚陈华钱胜耿经耳机", 2);
        String age = RandomUtil.randomNumbers(2);
        Date createTime = RandomUtil.randomDate(new Date(), DateField.DAY_OF_YEAR, -100, 100);
        Date updateTime = RandomUtil.randomDate(new Date(), DateField.DAY_OF_YEAR, -100, 100);
        jdbcTemplate.update("insert into sys_user (name,age,create_time,update_time) values (?,?,?,?)", name, age, createTime, updateTime);

    }


    @GetMapping("/query")
    public void query() {
        List<Map<String, Object>> dataList = jdbcTemplate.queryForList("select * from sys_user");
        System.out.println(JSONUtil.toJsonStr(dataList));
    }
}
